package se.kth.andreost;

import java.io.IOException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ChatClientAndroidActivity extends Activity {
	
	private TextView chat;
	private EditText textToSend;
	private Button sendButton;
	private ServerCommunicator comm;
	
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        this.chat = (TextView)findViewById(R.id.chat);
        this.textToSend = (EditText)findViewById(R.id.textToSend);
        this.sendButton = (Button)findViewById(R.id.send);
        comm = ((ChatClientApp)getApplication()).getServerCommunicator();
        new ServerListenerTask().execute();
        
        sendButton.setOnClickListener(new OnClickListener(
        		) {
			
			@Override
			public void onClick(View v) {
				sendMessage();
			}
		});
    
    }
    
    protected void sendMessage() {
    	String text = textToSend.getText().toString();
    	new SendMessageTask().execute(text);
    	
	}

	
	private class SendMessageTask extends AsyncTask<String, Void, Boolean> {
		
		private Dialog d;
		
		@Override
		protected void onPreExecute() {
			d = ProgressDialog.show(ChatClientAndroidActivity.this, null, "Skickar meddelande...");
		}
		
		@Override
		protected Boolean doInBackground(String... params) {
			return comm.write(params[0]);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			d.dismiss();
			if (!result){
				Toast.makeText(getApplicationContext(), "Meddelandet kunde inte skickas", Toast.LENGTH_SHORT);
				
			} else {
				chat.append("\nJag: " + textToSend.getText().toString());
				textToSend.setText("");
				
			}
		}
	}
    
    private class ServerListenerTask extends AsyncTask<Void, String, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			
			while (true){
				try {
					String inMessage = comm.readLine();
					if (inMessage == null){
						Toast.makeText(getApplicationContext(), "Servern har stängt anslutningen, du kan lika gärna stänga av appen", Toast.LENGTH_LONG);
						return null;
					}
					publishProgress(inMessage);
				} catch (IOException e) {
					Toast.makeText(getApplicationContext(), "Kunde inte läsa meddelande från servern", Toast.LENGTH_LONG);
					e.printStackTrace();
				}
			}
		}
		
		@Override
		protected void onProgressUpdate(String... values) {
			super.onProgressUpdate(values);
			chat.append("\n"+values[0]);
			
		}    	
    	
    }
}